import http from '@ohos.net.http';
import Log from '../utils/Logger'

const TAG = "HttpClient"

export enum ContentType {
  TEXT = "text/plain;charset=utf-8",
  JSON = "application/json",
  IMAGE = "image/jpeg",
}

export class HttpResponse {
  code: number = -1
  response: any
}

export const TIMEOUT_ID = -99; // 超时id

export class HttpClient {
  protected static httpRequest = http.createHttp();
  private static readonly TIMEOUT = 30000; // 30秒超时时间

  /*
   * 基础HTTP请求
   * @param URL 请求URL
   * @param method 请求方法
   * @param params 请求参数(JSON对象)
   * @param token 认证token(可选)
   */
  private static async request(
    URL: string,
    method: http.RequestMethod,
    params?: object,
    token?: string
  ): Promise<HttpResponse> {
    if (!this.httpRequest) {
      this.httpRequest = http.createHttp();
    }

    const headers: Record<string, string> = {
      'Content-Type': 'application/json'
    };

    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }

    const option: http.HttpRequestOptions = {
      method,
      header: headers,
      extraData: params
    };
    Log.info(TAG, `Request ${method} ${URL}`);

    const httpResponse = new HttpResponse();
    // 设置超时定时器
    const timeoutId = setTimeout(() => {
      httpResponse.code = TIMEOUT_ID;
      Log.warn(TAG, `Request timeout: ${URL}`);
    }, this.TIMEOUT);
    const data = await this.httpRequest.request(URL, option);
    clearTimeout(timeoutId); // 清除定时器
    httpResponse.code = data.responseCode;
    httpResponse.response = data.result;

    Log.info(TAG, `Request ${method} ${URL}`, JSON.stringify(httpResponse));
    return httpResponse;
  }

  /*
   * GET请求
   * @param URL 请求URL
   * @param params 请求参数(可选)
   * @param token 认证token(可选)
   */
  public static async httpGet(
    URL: string,
    token?: string
  ): Promise<HttpResponse> {
    return this.request(URL, http.RequestMethod.GET, {}, token);
  }

  /*
   * POST请求 
   * @param URL 请求URL
   * @param params 请求参数
   * @param token 认证token(可选)
   */
  public static async httpPost(
    URL: string,
    params: object,
    token?: string
  ): Promise<HttpResponse> {
    return this.request(URL, http.RequestMethod.POST, params, token);
  }
}